package cn.tedu._04weibo.controller;


import cn.tedu._04weibo.base.response.JsonResult;
import cn.tedu._04weibo.base.response.StatusCode;
import cn.tedu._04weibo.mapper.UserMapper;
import cn.tedu._04weibo.pojo.dto.UserLoginParam;
import cn.tedu._04weibo.pojo.dto.UserRegParam;
import cn.tedu._04weibo.pojo.entity.User;
import cn.tedu._04weibo.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/v1/user")
@Tag(name = "01-用户管理接口")
@Slf4j
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("reg")
    @Operation(summary = "用户注册接口")
    @ApiOperationSupport(order = 10)
    public JsonResult regInsetUser(@RequestBody UserRegParam userRegParam){
        log.debug("传入的参数："+userRegParam);
        String username = userRegParam.getUsername();
        int count =userMapper.selectUserByUsername(username);
        if(count>0){
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegParam,user);
        user.setCreateTime(new Date());
        int rows=userMapper.insertUser(user);
        if(rows<=0){
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
        return JsonResult.ok();
    }

    @PostMapping("login")
    @Operation(summary = "用户登录接口")
    @ApiOperationSupport(order = 20)
    public JsonResult loginUser(@RequestBody UserLoginParam userLoginParam, HttpSession session){
        log.debug("请求参数："+userLoginParam);
        UserVO userVO = userMapper.selectUserByUsernameAndPassword(userLoginParam);
        if(userVO==null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user",userVO);
        return JsonResult.ok(userVO);
    }

    @GetMapping("currentUser")
    @Operation(summary = "用户信息接口")
    @ApiOperationSupport(order = 30)
    public JsonResult currentUser(HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");
        log.debug("获取当前登录用户信息："+userVO);
        if (userVO==null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        log.debug("获取当前登录用户信息："+userVO);
        return JsonResult.ok(userVO);
    }

    @GetMapping("logout")
    @Operation(summary = "用户登出接口")
    @ApiOperationSupport(order = 40)
    public void logoutUser(HttpSession session){
        session.removeAttribute("user");
    }



}
